package com.eorchis.module.preauthorizationregistration.ui.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.Map;

import java.util.Calendar;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.eorchis.core.service.IBaseService;
import com.eorchis.core.springext.mvc.SessionConstant;
import com.eorchis.core.ui.commond.ResultState;
import com.eorchis.core.ui.controller.AbstractBaseController;
import com.eorchis.module.exceluitls.ReadExcelUtils;
import com.eorchis.module.exceluitls.domain.excel.ExcelSheet;
import com.eorchis.module.department.domain.Department;
import com.eorchis.module.deptassignedinfo.domain.DeptAssignedInfoBean;
import com.eorchis.module.deptassignedinfo.service.IDeptAssignedInfoService;
import com.eorchis.module.deptassignedinfo.ui.commond.DeptAssignedInfoQueryCommond;
import com.eorchis.module.preauthorizationregistration.domain.PreAuhorzaionQueryBean;
import com.eorchis.module.preauthorizationregistration.domain.PreSqSyUserBean;
import com.eorchis.module.preauthorizationregistration.service.IPreAuthorizationRegistrationService;
import com.eorchis.module.preauthorizationregistration.ui.commond.PreAuthorizationRegistrationQueryCommond;
import com.eorchis.module.preauthorizationregistration.ui.commond.PreAuthorizationRegistrationValidCommond;
import com.eorchis.module.signupdept.domain.SignupDept;
import com.eorchis.utils.utils.PropertyUtil;

/**
 * Title: PreAuthorizationRegistrationController<br>
 * Description: 个人报名预授权管理控制器<br>
 * Company: GoldGov<br>
 * Copyright @ 2012 GoldGov .All rights reserved.<br>
 * @author Administrator
 * @createDate 2015-01-06
 * @version $Revision$
 */
@Controller("preAuthorizationRegistrationController")
@RequestMapping(value = PreAuthorizationRegistrationController.MODULE_PATH)
public class PreAuthorizationRegistrationController extends AbstractBaseController<PreAuthorizationRegistrationValidCommond,PreAuthorizationRegistrationQueryCommond> {
	// 模块页面根路径
	public static final String MODULE_PATH = "/module/preauthorizationregistration";
	// 个人报名预授权接口
	@Resource(name = "com.eorchis.module.preauthorizationregistration.service.impl.PreAuthorizationRegistrationServiceImpl")
	private IPreAuthorizationRegistrationService preAuthorizationRegistrationService;
	@Autowired
	private ReadExcelUtils excelUtils;
	// 单位年度参学名额表接口
	@Resource(name = "com.eorchis.module.deptassignedinfo.service.impl.DeptAssignedInfoServiceImpl")
	private IDeptAssignedInfoService deptAssignedInfoService;
	
	@Override
	public IBaseService getService() {
		return preAuthorizationRegistrationService;
	}

	@Override
	public String getModulePath() {
		return MODULE_PATH;
	}
	/**
	 * 执行添加报名预授权
	 * @param vCommond
	 * @param request
	 * @param response
	 * @param resultState 
	 * @return
	 * @throws Exception
	 * @author NingSS
	 * @createDate 2015-1-6
	 */
	@RequestMapping(value = "/addPreAuthorizationRegistration")
	public String addPreAuthorizationRegistration(@ModelAttribute("result") @Valid PreAuthorizationRegistrationValidCommond vCommond,
			BindingResult bindingResult,HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception{
		resultState.setState(ResultState.RESULT_STATE_FAIL);//默认失败
		//获得登陆者的管理范围
		com.eorchis.module.security.cas.domain.Department department=(com.eorchis.module.security.cas.domain.Department)request.getSession().getAttribute(SessionConstant.CURRENT_SCOPE);
		if(PropertyUtil.objectNotEmpty(department)&&PropertyUtil.objectNotEmpty(department.getDeptID())){
			//判断传过来的参数
			if(PropertyUtil.objectNotEmpty(vCommond.getLoginId())){
				vCommond.setDeptId(department.getDeptID());
				//vCommond.setDeptId("8413");
				//调用service层
				String msg=preAuthorizationRegistrationService.addPreAuthorizationRegistration(vCommond);
				if("success".equals(msg)){
					resultState.setState(ResultState.RESULT_STATE_SUCCESS);//成功
					resultState.setMessage("添加成功！");
				}else{
					resultState.setMessage(msg);
				}
			}else{
				resultState.setMessage("登录号不能为空！");
			}
		}else{
			resultState.setMessage("获取管理范围失败！");
		}
		return "";
	}
	/**
	 * @return Excel导入报名预授权
	 * @throws Exception
	 * @author NingSS
	 * @date 2015-1-7
	 */
	@RequestMapping(value = "/importPreAuthorizationRegistration")
	public String importPreAuthorizationRegistration(HttpServletRequest request,@ModelAttribute("ResultSate")ResultState resultState,
			@ModelAttribute("resultList") PreAuthorizationRegistrationValidCommond vCommond)throws Exception{
		//获得登陆者的管理范围
		com.eorchis.module.security.cas.domain.Department department=(com.eorchis.module.security.cas.domain.Department)request.getSession().getAttribute(SessionConstant.CURRENT_SCOPE);
		if(PropertyUtil.objectNotEmpty(department)&&PropertyUtil.objectNotEmpty(department.getDeptID())){
			vCommond.setDeptId(department.getDeptID());
			//vCommond.setDeptId("8413");
			String msg="";
			MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
			Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
			for (MultipartFile mf : fileMap.values()) {
				CommonsMultipartFile cmf = (CommonsMultipartFile) mf;
				FileItem file = cmf.getFileItem();
				//File file = new File("D:\\导入报名预授权模板.xls");  
		        //FileInputStream item = new FileInputStream(file); 
				String name = file.getName();
				//byte[] bytes = null;
				if (name == null || name.trim().equals("")) {
					msg = "您使用的导入模板不正确，请确认后重新导入。";
				} else {
					String fileType = name.substring(name.lastIndexOf("."));
					if (!".xls".equals(fileType)) {
						msg="导入文件格式错误，应为.xls格式，请修改后重新导入。";
					} else {
						byte[] bytes = mf.getBytes();
						
						/*ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);  
			            byte[] b = new byte[1000];  
			            int n;  
			            while ((n = item.read(b)) != -1) {  
			                bos.write(b, 0, n);  
			            }  
			            item.close();  
			            bos.close();  
			            bytes = bos.toByteArray();*/
			            
						if (bytes.length == 0) {
							msg = "您使用的导入模板不正确，请确认后重新导入。";
						} else {
							//写解析bytes代码
							InputStream in = null;
							ExcelSheet sheet = null;
							in = new ByteArrayInputStream(bytes);
							//读取excel
							sheet=excelUtils.readFile(in);
							if(PropertyUtil.objectNotEmpty(sheet)){
								msg=preAuthorizationRegistrationService.importPreAuthorizationRegistration(vCommond, sheet);
							}else {
								msg = "您使用的导入模板不正确，请确认后重新导入。";
							}
						}
					}
				}
			}
			if ("".equals(msg)) {
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);
				resultState.setMessage("导入成功！");
			} else {
				resultState.setState(ResultState.RESULT_STATE_FAIL);
				resultState.setMessage(msg);
			}
		}
		return "";
	}
	/**
	 * 查询某部门所有已预授权的人的信息
	 * @param String
	 * @return
	 * @throws Exception
	 * @author Xupp
	 * @date 2015-1-8
	 */
	@RequestMapping(value = "/findPreAuthorZationRegistrationInfolist")
	public String findPreAuthorZationRegistrationInfolist(@ModelAttribute("result")PreAuthorizationRegistrationQueryCommond qCommond,
			BindingResult bindingResult,HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState)throws Exception{
		Department department = (Department) request.getSession()
				.getAttribute(SessionConstant.CURRENT_SCOPE);
		if(PropertyUtil.objectNotEmpty(department)&&PropertyUtil.objectNotEmpty(department.getDeptID())){
			qCommond.setSearchDeptId(department.getDeptID());
			qCommond.setResultList(preAuthorizationRegistrationService.findPreAuthorZationRegistrationInfolist(qCommond));
		}
		resultState.setMessage("操作成功！");
		resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		return "";
	}
	/**
	 * 查询某部门已授权人数和剩余人数
	 * @param String
	 * @return
	 * @throws Exception
	 * @author Xupp
	 * @date 2015-1-8
	 */
	@RequestMapping(value = "/findSqSyUserNum")
	public String findSqSyUserNum(@ModelAttribute("resultList")PreAuthorizationRegistrationQueryCommond qCommond,
			BindingResult bindingResult,HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState,Model model)throws Exception{
		Department department = (Department) request.getSession()
		.getAttribute(SessionConstant.CURRENT_SCOPE);
			List<?> list=null;
			if(PropertyUtil.objectNotEmpty(department)&&PropertyUtil.objectNotEmpty(department.getDeptID())){
				qCommond.setSearchDeptId(department.getDeptID());
				list=preAuthorizationRegistrationService.findPreAuthorZationRegistrationInfolist(qCommond);
			}
			DeptAssignedInfoQueryCommond queryCommond=new DeptAssignedInfoQueryCommond();
			queryCommond.setSearchDepId(department.getDeptID());
			//默认查询当前年
			if(!PropertyUtil.objectNotEmpty(queryCommond.getSearchYear())){
				Calendar a=Calendar.getInstance();  
				queryCommond.setSearchYear(a.get(Calendar.YEAR));
			}
		//查询限额
		if(deptAssignedInfoService.findDeptAssignedInfoList(queryCommond).size()>0){
			DeptAssignedInfoBean db=deptAssignedInfoService.findDeptAssignedInfoList(queryCommond).get(0);
			PreSqSyUserBean pb=new PreSqSyUserBean();
			pb.setSqUserNum(list.size());
			pb.setSyUserNum(db.getRestrictPersonNum()-list.size());
			model.addAttribute("result", pb);
			resultState.setMessage("操作成功！");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		}else{
			resultState.setMessage("查询为空！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
		return "";
	}
	/**
	 * 修改某部门某已预授权的人的姓名
	 * @param String
	 * @return
	 * @throws Exception
	 * @author Xupp
	 * @date 2015-1-8
	 */
	@RequestMapping(value = "/updatePreAuthorZationRegistrationInfolist")
	public String updatePreAuthorZationRegistrationInfolist(@ModelAttribute("result")PreAuthorizationRegistrationValidCommond vCommond,
			BindingResult bindingResult,HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception{
		int count=preAuthorizationRegistrationService.updatePreAuthorZationRegistrationInfolist(vCommond);
		if(count>=0){
			resultState.setMessage("操作成功！");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		}else{
			resultState.setMessage("系统错误，请联系管理员！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
		return "";
	}
	/**
	 * 撤销某部门某已预授权的人的姓名
	 * @param String
	 * @return
	 * @throws Exception
	 * @author Xupp
	 * @date 2015-1-8
	 */
	@RequestMapping(value = "/deletePreAuthorZationRegistrationInfolist")
	public String deletePreAuthorZationRegistrationInfolist(@ModelAttribute("resultList")PreAuthorizationRegistrationQueryCommond qCommond,
			BindingResult bindingResult,HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception{
		if(PropertyUtil.objectNotEmpty(qCommond.getSearchUserIds())){
			int count=preAuthorizationRegistrationService.deletePreAuthorZationRegistrationInfolist(qCommond);
			if(count>=0){
				resultState.setMessage("操作成功！");
				resultState.setState(ResultState.RESULT_STATE_SUCCESS);
			}else{
				resultState.setMessage("系统错误，请联系管理员！");
				resultState.setState(ResultState.RESULT_STATE_FAIL);
			}
		}else{
			resultState.setMessage("系统错误，请联系管理员！");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}
		return "";
	}
	/**
	 * 预某部门某已预授权的人
	 * @param String
	 * @return
	 * @throws Exception
	 * @author Xupp
	 * @date 2015-1-8
	 */
	@RequestMapping(value = "/prePreAuthorZationRegistrationInfo")
	public String prePreAuthorZationRegistrationInfo(@ModelAttribute("result")PreAuthorizationRegistrationValidCommond vCommond,
			BindingResult bindingResult,HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState) throws Exception{
		PreAuhorzaionQueryBean pqb=preAuthorizationRegistrationService.prePreAuthorZationRegistrationInfo(vCommond);
		if(!PropertyUtil.objectNotEmpty(pqb)){
			resultState.setMessage("系统错误，请联系管理员!");
			resultState.setState(ResultState.RESULT_STATE_FAIL);
		}else{
			SignupDept sd=new SignupDept();
			sd.setDepname(pqb.getDeptName());
			vCommond.setDepartment(sd);
			vCommond.setLoginId(pqb.getLoginId());
			vCommond.setUserName(pqb.getUserName());
			resultState.setMessage("");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		}
		return "";
	}
	
	/**
	 * 查询某部门已报人数，和剩余人数
	 * @param String
	 * @return
	 * @throws Exception
	 * @author Max
	 * @date 2015-1-14
	 */
	@RequestMapping(value = "/findSignUNumByDepId")
	public String findSignUNumByDepId(@ModelAttribute("resultList")PreAuthorizationRegistrationQueryCommond qCommond,
			BindingResult bindingResult,HttpServletRequest request,HttpServletResponse response,
			@ModelAttribute("resultState") ResultState resultState,Model model)throws Exception{
		    Department department = (Department) request.getSession().getAttribute(SessionConstant.CURRENT_SCOPE);
		    qCommond.setSearchDeptId(department.getDeptID());
		    PreSqSyUserBean bean=preAuthorizationRegistrationService.findSignUNumByDepId(qCommond);
			model.addAttribute("result", bean);
			resultState.setMessage("操作成功！");
			resultState.setState(ResultState.RESULT_STATE_SUCCESS);
		return "";
	}
	
}
